// 通过ID找到按钮
const button = document.getElementById("export-btn");
const input = document.getElementById("csrf-token");
const operInfo = document.getElementById("oper-info");

// 基础请求
function request(url) {
	return fetch(url, {
		headers: {
			"csrf-token": input.value
		}
	}).then(res => res.json());
}

// api
function getList(limit) {
	const url = `https://corplink-mgt.miracle.ac.cn:8443/api/admin/v1/vpn/acl/resource/list?key=&limit=${limit}&offset=0&os=web&type=&used_type=0`;
	return request(url);
}

function getDetail(limit, resourceId) {
	const url = `https://corplink-mgt.miracle.ac.cn:8443/api/admin/v1/vpn/acl/policy/list?expired_status=0&key=&limit=${limit}&offset=0&os=web&resource_id=${resourceId}&sort=0&type=`;
	return request(url);
}

async function getItem(getData, ...rest) {
	const { data: { count } } = await getData(0, ...rest);
	const { data } = await getData(count, ...rest);
	return data;
}

function download(file, filename) {
	let url = URL.createObjectURL(file);
	let a = document.createElement('a');
	a.href = url;
	a.download = filename; 
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
	URL.revokeObjectURL(url);
}

function setStyle(sheet) {
	const _titleCell = sheet.getRow(1);
	_titleCell.height = 19;
	_titleCell.eachCell((cell, colIdx) => {
		cell.font = {
			name: "等线",
			bold: true,
			size: 14,
		}
		cell.alignment = {
		    vertical: "middle",
		    horizontal: "center",
		};
		cell.border = {
		    top: {
		        style: "thin",
		        color: {
		            argb: "FF000000",
		        },
		    },
		    left: {
		        style: "thin",
		        color: {
		            argb: "FF000000",
		        },
		    },
		    bottom: {
		        style: "thin",
		        color: {
		            argb: "FF000000",
		        },
		    },
		    right: {
		        style: "thin",
		        color: {
		            argb: "FF000000",
		        },
		    },
		};
		cell.fill = {
		    type: "pattern",
		    pattern: "solid",
		    fgColor: {
		        argb: "ffffff00",
		    },
		};
	})
	
	sheet.eachRow((row, rowNumber) => {
		if (rowNumber === 1) return;
		row.height = 100;
		row.eachCell(cell => {
			cell.font = {
				name: "等线",
				size: 11,
			}
			cell.alignment = {
			    vertical: "middle",
			    horizontal: "center",
					wrapText: true
			};
			cell.border = {
			    top: {
			        style: "thin",
			        color: {
			            argb: "FF000000",
			        },
			    },
			    left: {
			        style: "thin",
			        color: {
			            argb: "FF000000",
			        },
			    },
			    bottom: {
			        style: "thin",
			        color: {
			            argb: "FF000000",
			        },
			    },
			    right: {
			        style: "thin",
			        color: {
			            argb: "FF000000",
			        },
			    },
			};
		})
	})
}

function handlerExecl(data) {
	const _workbook = new ExcelJS.Workbook();
	const _sheet1 = _workbook.addWorksheet('sheet1');
	_sheet1.columns = [
	    { header: "网络资源", key: "addrs", width: 25 },
	    { header: "端口", key: "ports", width: 30 },
	    { header: "协议", key: "protocols", width: 20 },
	    { header: "网路资源名称", key: "key", width: 80 },
	    { header: "访问策略名", key: "policy_key", width: 80 },
	    { header: "部门", key: "departments", width: 50 },
	    { header: "个人", key: "users", width: 50 },
	];
	data.forEach(item => _sheet1.addRow(item));
	setStyle(_sheet1);
	_workbook.xlsx.writeBuffer().then((buffer) => {
		let file = new Blob([buffer], {
      type: "application/octet-stream",
    })
		
		download(file, '飞连VPN列表.xlsx')
	})
}

function chunkArray(array, chunkSize) {
  const chunks = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    chunks.push(array.slice(i, i + chunkSize));
  }
  return chunks;
}

async function dataHandler(data, { addrs, ports, protocols, key, id }) {
	const empty = 'None';
	const { items } = await getItem(getDetail, id);
	addrs = addrs?.join("\n") || empty;
	ports = ports?.join("\n") || empty;
	protocols = protocols?.join("\n") || empty;
	const policy_keys = items.map(item => item.policy_key);
	const departments = items.map(item => item.departments?.map(item => item.name)).flat(1);
	const users = items.map(item => item.users?.map(item => item.full_name)).flat(1);
	data.push({
		addrs, 
		ports, 
		protocols, 
		key, 
		policy_key: policy_keys.length ? policy_keys.join("\n") : empty, 
		departments: departments.length ? departments.join("\n") : empty, 
		users: users.length ? users.join("\n") : empty
	})
}

button.addEventListener("click", async () => {
	let data = [];
	operInfo.innerHTML = '正在执行导出...';
	try {
		const { items } = await getItem(getList);
		const itemsChunk = chunkArray(items, 6);
		for (const itemChunk of itemsChunk) {
			await Promise.all(itemChunk.map(item => dataHandler(data, item)))
		}
		operInfo.innerHTML = '导出成功.';
		operInfo.style.color = '#009a61';
		handlerExecl(data);
	} catch(e) {
		operInfo.innerHTML = '请求错误，请打开插件控制台检查';
		operInfo.style.color = '#f53f3f';
	}

});
